library IEEE;
use IEEE.std_logic_1164.all;
use ieee.std_logic_unsigned.all; 
use ieee.std_logic_arith.all;

entity SUM_1_8_7 is port(
	RST  : in  std_logic;
	CLK  : in  std_logic;
	CLR  : in  std_logic;
	DINA : in  std_logic_vector(15 downto 0);
	DINB : in  std_logic_vector(15 downto 0);
	DOUT : out std_logic_vector(15 downto 0));
end SUM_1_8_7;

architecture UNSIGNED_SUM of SUM_1_8_7 is

signal X : std_logic_vector(8 downto 0);
signal Y : std_logic_vector(6 downto 0);
signal F : std_logic;
signal xDOUT : std_logic_vector(15 downto 0);

begin
	
	process(DINA, DINB)
	variable i : integer;
	variable j : integer;
	begin
		i := Conv_integer(DINA(6 downto 0));
		j := Conv_integer(DINB(6 downto 0));
		if(i > j + 7)then
			F <= '0';
			X <= '0' & DINA(14 downto 7);
			Y <= DINA(6 downto 0);
		elsif(j > i + 7)then
			F <= '0';
			X <= '0' & DINB(14 downto 7);
			Y <= DINB(6 downto 0);
		else
			F <= '1';
			if i > j then
				X <= ('0' & DINA(14 downto 7)) + DINB(14 downto 7+i-j) + ('1' and DINB(7+i-j-1));
				Y <= DINA(6 downto 0);
			elsif i < j then
				X <= ('0' & DINB(14 downto 7)) + DINA(14 downto 7-i+j) + ('1' and DINA(7-i+j-1));
				Y <= DINB(6 downto 0);
			else
				X <= ('0' & DINB(14 downto 7)) + DINA(14 downto 7);
				Y <= DINB(6 downto 0);
			end if;
		end if;	
	end process;
	
	process(X,Y,F)
	begin
		xDOUT(15) <= '0';
		
		if(F = '0') then
			xDOUT (14 downto 7) <= X(7 downto 0);
			xDOUT (6 downto 0)  <= Y;
		elsif (F = '1') then
			if(X(8) = '1') then
				xDOUT (14 downto 7) <= X(8 downto 1);
				xDOUT (6 downto 0) <= Y + '1';
			elsif(X(8) = '0') then
				xDOUT (14 downto 7) <= X(7 downto 0);
				xDOUT (6 downto 0) <= Y;
			end if;
		end if;	
	end process;
	
	process(RST, CLK, CLR)
	begin
		if RST = '1' then
			DOUT <= x"0000";
		elsif Rising_edge(CLK) then
			if CLR = '0' then
				DOUT <= xDOUT;
			else
				DOUT <= DINA;
			end if;
		end if;
	end process;
	
end UNSIGNED_SUM;